<template>
  <view class="content">
    <template v-if="isCertified">
      <uni-list>
        <uni-list-item class="item" title="姓名" :rightText="realName"></uni-list-item>
        <uni-list-item class="item" title="身份证号码" :rightText="idCard"></uni-list-item>
      </uni-list>
    </template>
    <template v-else>
      <uni-frv-external-realname
        ref="frv"
        :agreement="agreement"
        @start="startVerify"
        @finish="verifyFinish"
      ></uni-frv-external-realname>
    </template>
  </view>
</template>

<script>
export default {
  data() {
    return {
      agreement: {
        title: "实名认证协议",
        url: "https://www.xxxxx.com"
      },
      isCertified: false,
      realName: "",
      idCard: ""
    };
  },
  methods: {
    async startVerify({ realName, idCard, metaInfo }) {
      uni.showLoading({
        title: "加载中..."
      });
      uni.request({
        url: "YOUR_BACKEND_API/getCertifyId",
        method: "POST",
        data: {
          realName,
          idCard,
          metaInfo
        },
        success: ({ data }) => {
          if (data.errCode !== 0) {
            return uni.showModal({
              title: data.errCode,
              content: data.errMsg,
              showCancel: false
            });
          }
          if (data.certifyId) {
            this.$refs.frv.startFacialRecognitionVerify(data.certifyId);
          }
        },
        fail: error => {
          console.error(error.errMsg);
          uni.showModal({
            content: "请求异常，稍后再试",
            showCancel: false
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
    async verifyFinish(result) {
      uni.showLoading({
        title: "加载中..."
      });
      uni.request({
        url: "YOUR_BACKEND_API/getAuthResult",
        method: "POST",
        data: {
          certifyId: result.certifyId
        },
        success: ({ data }) => {
          if (data.errCode !== 0) {
            return uni.showModal({
              title: data.errCode,
              content: data.errMsg,
              showCancel: false
            });
          }

          uni.showModal({
            content: "实名认证成功",
            showCancel: false,
            success: () => {
              this.isCertified = true;
              this.realName = data.realName;
              this.idCard = data.idCard;
            }
          });
        },
        fail: error => {
          uni.showModal({
            content: "请求异常，稍后再试",
            showCancel: false
          });
          console.error(error.errMsg);
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  }
};
</script>

<style>
</style>